# -*- coding:utf-8 -*-
# File: cputemp.py
# 向平台已经创建的数据流发送数据点
import urllib.request
import urllib.error
import json
import datetime
import serial  # 导入串口包
import sqlite3
import time  # 导入时间包

APIKEY = 'lFbWSrmunyEXMx==M7pMyOro=kI='  # 改成你的APIKEY
# ser = serial.Serial("/devyAMA0", 9600)
ser = serial.Serial("COM7", 115200, timeout=5)
ser.flushInput()
def http_put():
    CurTime = datetime.datetime.now()
    while True:

        count = ser.inWaiting() # 获取串口缓冲区数据

        if count !=0 :

            recvs = ser.read(ser.in_waiting).decode("utf-8").split(':')[1]
            # 读出串口数据，数据采用gbk编码
            recv = str(recvs).split('C')[0]

            url = 'http://api.heclouds.com/devices/834256498/datapoints'
            values = {'datastreams': [{"id": "wendu", "datapoints": [{"at": CurTime.isoformat(), "value": recv}]}]}

            jdata = json.dumps(values).encode(encoding='UTF8')  # 对数据进行JSON格式化编码
        # 打印json内容
            print(jdata)
            request = urllib.request.Request(url, jdata)
            request.add_header('api-key', APIKEY)
            request.get_method = lambda: 'POST'  # 设置HTTP的访问方式
            request = urllib.request.urlopen(request)
            con = sqlite3.connect('user.db')
            c = con.cursor()
            c.execute("INSERT INTO DEVICE (time,temp)values ('{}','{}')".format(CurTime.isoformat(), recv))
            con.commit()
            con.close()
            return request.read()
        time.sleep(0.1)  # 延时0.1秒，免得CPU出问题

while True:
        time.sleep(5)
        resp = http_put()
        print ("OneNET_result: %s" %resp)
